package net.atomarrow.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * html工具类
 * @author Michael
 *
 */
public class HtmlUtil {
	/**
	 * 生成静态页
	 * @param templatePath 模板地址及模板名称
	 * @param pageFolder 生成html页面文件夹
	 * @param contentMap 替换内容
	 * @return 文件名
	 */
	public static String makeHtml(String templatePath,String pageFolder,Map<String,String>contentMap){
		String filename="";
		try {
			
			String templateContent = "";
			FileInputStream fileinputstream = new FileInputStream(templatePath);//读取模块文件
			int lenght = fileinputstream.available();
			byte[] bytes = new byte[lenght];
			fileinputstream.read(bytes);
			fileinputstream.close();
			templateContent = new String(bytes, StandardCharsets.UTF_8);
			
			
			Iterator<String> iter = contentMap.keySet().iterator();
			while(iter.hasNext()){
				String s = iter.next();
				templateContent = templateContent.replaceAll(s,
						contentMap.get(s));
            }
			Calendar calendar = Calendar.getInstance();
			filename = (int)(Math.random()*100)+""+calendar.getTimeInMillis()
					+ ".html";
			if(pageFolder.endsWith("/")||pageFolder.endsWith("\\")){
				pageFolder = pageFolder + filename;//生成的html文件保存路径
			}else{
				pageFolder = pageFolder + "/"+filename;//生成的html文件保存路径
			}
			FileOutputStream fileoutputstream = new FileOutputStream(
					pageFolder);//建立文件输出流
			byte[] tag_bytes = templateContent.getBytes(StandardCharsets.UTF_8);
			fileoutputstream.write(tag_bytes);
			fileoutputstream.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return filename;
	}
	/**
	 * 生成静态页
	 * @param templatePath 模板地址及模板名称
	 * @param pageFolder 生成html页面文件夹
	 * @param filename 指定文件名
	 * @param contentMap 替换内容
	 * @return 是否成功状态
	 */
	public static boolean makeHtml(String templatePath,String pageFolder,String filename,Map<String,String>contentMap){
		try {
			
			String templateContent = "";
			FileInputStream fileinputstream = new FileInputStream(templatePath);//读取模块文件
			int lenght = fileinputstream.available();
			byte[] bytes = new byte[lenght];
			fileinputstream.read(bytes);
			fileinputstream.close();
			templateContent = new String(bytes, StandardCharsets.UTF_8);
			
			
			Iterator<String> iter = contentMap.keySet().iterator();
			while(iter.hasNext()){
				String s = iter.next();
				templateContent = templateContent.replaceAll(s,
						contentMap.get(s));
            }
			Calendar calendar = Calendar.getInstance();
			if(pageFolder.endsWith("/")||pageFolder.endsWith("\\")){
				pageFolder = pageFolder + filename;//生成的html文件保存路径
			}else{
				pageFolder = pageFolder + "/"+filename;//生成的html文件保存路径
			}
			
			FileOutputStream fileoutputstream = new FileOutputStream(
					pageFolder);//建立文件输出流
			byte[] tag_bytes = templateContent.getBytes(StandardCharsets.UTF_8);
			fileoutputstream.write(tag_bytes);
			fileoutputstream.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 处理掉script标签
	 * @param str
	 * @return
	 */
	public static String processScript(String str){
	    if(str==null){
	        return null;
	    }
	    return str.replaceAll("<script", "&lt;script").replaceAll("</script", "&lt;/script");
	}
	
/*	public static void main(String args[]) {
		String title = "jsp生成静态html文件";
		String content = "小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？小样，还搞不定你？";
		String editer = "撒旦法f";
		Map<String,String> map = new HashMap<String,String>();
		map.put("###news.content###", content);
		map.put("###news.title###", title);
		map.put("###news.author###", editer);
		map.put("###news.time###", "2010-10-10");
		
		
//		String name = HtmlMaker.makeHtml("E:\\html\\newscontent.jsp", "d:\\", map);
//		System.out.println(name);
//		
		
		boolean b = HtmlMaker.makeHtml("D:\\workspace\\BaseFrameWork\\WebRoot\\template.jsp", "D:\\workspace\\BaseFrameWork\\WebRoot\\","123.jsp", map);
		System.out.println(b);
		
		
	}*/
	    private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
	    private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
	    private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
	    private static final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符
	    
	    /**
	     * @param htmlStr
	     * @return
	     *  删除Html标签
	     */
	    private static String delHTMLTag(String htmlStr) {
	        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
	        Matcher m_script = p_script.matcher(htmlStr);
	        htmlStr = m_script.replaceAll(""); // 过滤script标签

	        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
	        Matcher m_style = p_style.matcher(htmlStr);
	        htmlStr = m_style.replaceAll(""); // 过滤style标签

	        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
	        Matcher m_html = p_html.matcher(htmlStr);
	        htmlStr = m_html.replaceAll(""); // 过滤html标签

	        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
	        Matcher m_space = p_space.matcher(htmlStr);
	        htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
	        return htmlStr.trim(); // 返回文本字符串
	    }
	    
	    public static String getTextFromHtml(String htmlStr){
	        if(htmlStr==null){
	            return null;
	        }
	        htmlStr = delHTMLTag(htmlStr);
	        htmlStr = htmlStr.replaceAll("&nbsp;", "");
	        return htmlStr;
	    }
	    public static String getTextFromHtml(String htmlStr,int length){
	        String str = getTextFromHtml(htmlStr);
	        if(str==null){
	            return str;
	        }
	        if(str.length()<=length){
	            return str;
	        }
	        return str.substring(0,length);
	    }
	    
//	    public static void main(String[] args) {
//	        String str = "<div style='text-align:center;'>&nbsp;整治“四风”&nbsp;&nbsp;&nbsp;清弊除垢<br/><span style='font-size:14px;'>&nbsp;</span><span style='font-size:18px;'>公司召开党的群众路线教育实践活动动员大会</span><br/></div>";
//	        System.out.println(getTextFromHtml(str,10));
//	        System.out.println("sdf");
//	    }

}
